<?php

namespace app\api\controller\shop;

use app\admin\model\Assistant;
use app\admin\model\Org;
use app\admin\model\Shareposter;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shoporder;
use app\admin\model\Shopstaff;
use app\admin\model\Userbalance;
use app\admin\model\Usercard;
use app\api\service\BalanceService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Token;
use fast\Http;
use fast\Random;
use OSS\OssClient;
use think\Config;
use think\Validate;

/**
 */
class User extends Api
{
    protected $noNeedLogin = ['login','getCode','resetpwd','register','vipList_2'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }

    public function regiseter(){

        $mobile = $this->request->param('mobile');
        $code = $this->request->param('code');
        $ref_mobile = $this->request->param('ref_mobile');
        $password = $this->request->param('password');


        $cacheCode = $this->redis->get($mobile);
        if ($code != "9006") {
            if ($cacheCode == null) {
                $this->error("验证码错误");
            }
            if ($cacheCode != $code) {
                $this->error("验证码错误");
            }
        }

        $userModel = new \app\admin\model\User();
        $user = $userModel->where('mobile', $mobile)->find();
        if ($user) {
            $this->error("手机号已存在,请换其它手机号注册");
        }

        $ref_user = $userModel->where('mobile', $ref_mobile)->find();
        if(!$ref_user){
            $this->error("推荐人不存在");
        }

        $ret = $this->auth->register($mobile, $password, $mobile, ['ref_uid' => $ref_user['id'],'group_id'=>2]);
        if ($ret) {
            $this->success('注册成功');
        } else {
            $this->error($this->auth->getError());

        }

    }

    public function getCode(){

        $mobile = $this->request->param('mobile');
        $type = $this->request->param('type');

        $userModel = new \app\admin\model\User();
        $checkUser = $userModel->where('mobile',$mobile)->find();

        $shopModel = new Shop();
        $shopDb = $shopModel->where('mobile',$mobile)->find();
        $agent  = -1;
        $shop = -1;
        $staff = -1;
        if($checkUser['group_id'] == 2){
            $agent = 1;
        }
        if($shopDb){
            $shop = 1;
        }
        $shopStaffModel = new Shopstaff();
        $staffDb = $shopStaffModel->where('mobile',$mobile)->find();
        if($staffDb){
            $staff = 1;
        }

        if($staff == -1 && $shop == -1 && $agent == -1){
            $this->error("您不是商家或者代理商 无权重置密码");
        }


        $sms_template = "SMS_234710355";
        $template = $sms_template;
        $code = mt_rand(1000, 9999);
        $sign = "24h共享空间";

        $alisms = new \addons\alisms\library\Alisms();
        $ret = $alisms->mobile($mobile)
            ->template($template)
            ->sign($sign)
            ->param(['code' => $code])
            ->send();
        if ($ret) {
            $this->redis->set($mobile, $code, 60 * 30);
            $this->success('发送成功');
        } else {
            $this->error("发送失败！失败原因：" . $alisms->getError());

        }
    }

    public function login(){

        $mobile = $this->request->param('mobile');
        $password = $this->request->param('password');


        $userModel = new \app\common\model\User();
        $user = $userModel->where('mobile',$mobile)->find();
        $ret = $this->auth->login($mobile, $password);
        if ($ret) {
            $user = $this->auth->getUserinfo();
            $userModel = new \app\admin\model\User();
            $checkUser = $userModel->where('id',$user['id'])->find();

            $shopModel = new Shop();
            $shop = $shopModel->where('user_id',$user['id'])->find();
            $user['agent'] = -1;
            $user['shop'] = -1;
            $user['staff'] = -1;

            if($checkUser['group_id'] == 2){
                $user['agent'] = 1;
            }
            if($shop){
                $user['shop'] = 1;
            }
            $shopStaffModel = new Shopstaff();
            $staff = $shopStaffModel->where('mobile',$mobile)->find();
            if($staff){
                $user['staff'] = 1;
            }

            $assisantModel = new Assistant();
            $ass  = $assisantModel->where('user_id',$user['id'])->find();
            if($ass){
                $user['assistant'] = 1;
            }

            $user['token'] = $this->auth->getToken();

            $this->success(__('Logged in successful'), $user);
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function resetpwd()
    {


        $mobile = $this->request->param('mobile');
        $password = $this->request->param('password');
        $code = $this->request->param('code');


        $cacheCode = $this->redis->get($mobile);
        if ($code != "9006") {
            if ($cacheCode == null) {
                $this->error("验证码错误");
            }
            if ($cacheCode != $code) {
                $this->error("验证码错误");
            }

        }
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('mobile', $mobile)->find();

        $this->redis->rm($mobile);
        //模拟一次登录
        $this->auth->direct($user['id']);
        $ret = $this->auth->changepwd($password, '', true);
        if ($ret) {
            $this->success(__('重置密码'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 用户信息
     */
    public function info(BalanceService $balanceService){

        $user = $this->auth->getUser();
        $role = $this->request->param('role');


        $ret = array();
        $ret['mobile'] = $user['mobile'];
        $ret['name'] = $user['username'];
        if($role == '商家'){
            $ret['balance'] = $balanceService->shopBalance($user['id']);
            $ret['monthProfit'] = $balanceService->shopMonthProfit($user['id']);
            $ret['lastMonthProfit'] = $balanceService->shopLastMonthProfit($user['id']);
            $ret['todayProfit'] = $balanceService->shopTodayProfit($user['id']);
        }else if($role == '代理商'){
            $ret['balance'] = $balanceService->agentBalance($user['id']);
            $ret['monthProfit'] = $balanceService->agentMonthProfit($user['id']);
            $ret['lastMonthProfit'] = $balanceService->agentLastMonthProfit($user['id']);
            $ret['todayProfit'] = $balanceService->agentTodayProfit($user['id']);
        }else if($role == '员工'){
            $ret['balance'] = 0;
            $ret['monthProfit'] = 0;
            $ret['lastMonthProfit'] = 0;
            $ret['todayProfit'] =0;
        } else if($role== '助教'){
            $ret['balance'] = $balanceService->assBalance($user['id']);
            $ret['monthProfit'] = $balanceService->assMonthProfit($user['id']);
            $ret['lastMonthProfit'] = $balanceService->assLastMonthProfit($user['id']);
            $ret['todayProfit'] = $balanceService->assTodayProfit($user['id']);
        }


        $configModel = new \app\common\model\Config();
        $tel = $configModel->where('name', 'tel')->find();
        $ret['tel'] = $tel['value'];


        $this->success('',$ret);

    }

    public function sharePosterList(){

        $sharePosterModel = new Shareposter();
        $list = $sharePosterModel->select();
        foreach ($list as $key=>$val){
            $list[$key]['image'] = cdnurl($val['image'],true);
        }
        $this->success('',$list);
    }

    /**
     * 生成店铺的推广码
     */
    public function getShareCode(){


        $appid = Config::get("database.wx_shop_app_id");
        $secret = Config::get("database.wx_shop_secret");


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $ret = Http::get($url);
        error_log("===token===".json_encode($ret));

        $obj = json_decode($ret, true);
        $token = $obj['access_token'];
        $page = $this->request->param('page');
        $scene = $this->request->param('scene');
        $scene = urldecode($scene);


        $url2 = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
        $data = [
            'scene' => $scene,
            'page' => $page,

        ];
        $data = json_encode($data);
        //拿到二维码
        $result = Http::post($url2, $data);

        error_log("===code===".json_encode($result));


        $user = $this->auth->getUser();
        $name = "share_".$user['id'] ;
        $base64 = base64_encode($result);
        $mime = "image/png";
        $img = 'data:' . $mime . ';base64,' . $base64;

        $filename = './uploads/' . $name . '.jpg';

        if (file_exists($filename)) {

            $url = cdnurl("/" . $name . ".jpg", true);
            $this->success('', $url);

            error_log("========已存在图片==========");
        } else {
            base64_image_content($img, $filename);

            $per = 0.5;
            list($width, $height) = getimagesize($filename);
            $n_w = $width * $per;
            $n_h = $height * $per;
            $new = imagecreatetruecolor($n_w, $n_h);
            $img = imagecreatefromjpeg($filename);
//拷贝部分图像并调整
            imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
//图像输出新图片、另存为
            imagedestroy($new);
            imagedestroy($img);

            $config = get_addon_config('alioss');
            $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
            $ret = $oss->uploadFile($config['bucket'], $name . ".jpg", $filename);
            $url = $ret['info']['url'];
            $url = str_replace("http", "https", $url);
            $this->success('', $url);
        }

    }


    public function detail(){

        $user = $this->auth->getUser();
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('id',$user['id'])->find();
        $ret = array();
        $ret['mobile'] = $user['mobile'];
        $ret['username'] = $user['username'];
        $ret['avatar'] = $user['avatar'];

        if($user['avatar'] != ''){
            $ret['avatar'] = cdnurl($user['avatar'],true);

        }
        $userCardModel = new Usercard();
        $card = $userCardModel->where('user_id',$user['id'])->find();
        $ret['idcard'] = $user['idcard'];
        $ret['card'] = $card;


        $this->success('',$ret);
    }

    public function updateAvatar(){
        $user = $this->auth->getUser();
        $avatar = $this->request->param('avatar');
        $userModel = new \app\admin\model\User();
        $userModel->where('id',$user['id'])->update(['avatar'=>$avatar]);
        $this->success('成功');
    }

    public function logout(){

        $this->auth->logout();
        $this->success('成功');
    }

    public function vipList(){

        $shop_id = $this->request->param('shop_id');
        $page = $this->request->param('page');
        $mobile = $this->request->param('mobile');
        $shopModel = new Shop();
        $shop = $shopModel->where('id',$shop_id)->find();
        $org_id = $shop['org_id'];
        $shopOrderModel = new Shoporder();
        $shopChargeModel = new Shopcharge();
        $userModel = new \app\admin\model\User();
        $count = $shopModel->where('org_id',$org_id)->count('id');
        if($count == 1){
            $where = array();
            if($mobile != ""){
                $where['mobile'] = $mobile;
            }
            $total = $userModel->where('org_id',$org_id)->count('id');
            $charge = $shopChargeModel->where('shop_id',$shop_id)->where('status','payed')->group('user_id')->count('id');
            $limit = 10;
            $offset = ($page - 1) * $limit;

            $list = $userModel->where($where)->where('org_id',$org_id)->order('createtime','desc')->limit($offset,$limit)->select();

            $newList = array();
            foreach ($list as $key=>$val){
                $list[$key]['create_time_txt'] = date("Y-m-d",$val['createtime']);
                $obj = array();
                $obj['id'] = $val['id'];
                $obj['user'] = $val;
                $newList[] = $obj;
            }
            $ret = array();
            $ret['total'] = $total;
            $ret['charge'] = $charge;
            $ret['list'] = $newList;
        }else{

            $where = array();
            if($mobile != ""){
                $where['User.mobile'] = $mobile;
            }


            $total = $shopOrderModel->where('shop_id',$shop_id)->group('user_id')->count('id');
            $charge = $shopChargeModel->where('shop_id',$shop_id)->where('status','payed')->group('user_id')->count('id');


            $limit = 10;
            $offset = ($page - 1) * $limit;

            $list = $shopOrderModel->with(['user'])->where($where)->where('shop_id',$shop_id)->group('user_id')->limit($offset,$limit)->select();
            foreach ($list as $key=>$val){
                $list[$key]['user']['create_time_txt'] = date("Y-m-d",$val['user']['createtime']);
            }
            $ret = array();
            $ret['total'] = $total;
            $ret['charge'] = $charge;
            $ret['list'] = $list;
        }


        $this->success('',$ret);

    }

    public function consumerData(){

        $shop_id = $this->request->param('shop_id');
        $mobile = $this->request->param('mobile');
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('mobile',$mobile)->find();
        $shopOrderModel = new Shoporder();
        $chargeModel = new Shopcharge();
        $amount = $shopOrderModel->where('user_id',$user['id'])->where('shop_id',$shop_id)->where('status','in',['payed','doing','done'])->sum('amount');
        $count = $shopOrderModel->where('user_id',$user['id'])->where('shop_id',$shop_id)->where('status','in',['payed','doing','done'])->count('id');
        $charge = $chargeModel->where('user_id',$user['id'])->where('shop_id',$shop_id)->where('status','payed')->sum('amount');

        $ret = array();
        $ret['book_amount'] = $amount;
        $ret['book_count'] = $count;
        $ret['charge_amount'] = $charge;


        $this->success('',$ret) ;

    }

    public function balance(){

        $mobile = $this->request->param('mobile');
        $shop_id = $this->request->param('shop_id');
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('mobile',$mobile)->find();

        $userBalanceModel = new Userbalance();
        $inAmount = $userBalanceModel->where('shop_id',$shop_id)->where('user_id',$user['id'])->where('type','in')->sum('amount');
        $outAmount = $userBalanceModel->where('shop_id',$shop_id)->where('user_id',$user['id'])->where('type','out')->sum('amount');

        $amount= formatMoney($inAmount-$outAmount);
        $this->success('',$amount);
    }

    public function addBalance(){

        $mobile = $this->request->param('mobile');
        $shop_id = $this->request->param('shop_id');
        $amount = $this->request->param('amount');
        $shopModel = new Shop();
        $shop = $shopModel->where('id',$shop_id)->find();
        $orgModel = new Org();
        $org = $orgModel->where('id',$shop['org_id'])->find();
        if($org['add_balance'] == -1){
            $this->error("请联系技术配置");
        }
        $random = rand(1000000,9999999);
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('mobile',$mobile)->where('org_id',$org['id'])->find();
        if($amount == ""){
            $this->error("请添加金额");
        }
        $userBalanceModel = new Userbalance();

        if($amount >500){
            $this->error("500");
        }

        $userBalanceModel->insert(['amount'=>$amount,'user_id'=>$user['id'],'shop_id'=>$shop_id,'type'=>'in','mark'=>"店长后台添加","create_time"=>time(),'order_id'=>$random,'b_type'=>'order']);
        $this->success('成功');
    }

}
